package com.tehui.fragment.impl;

import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.support.annotation.IdRes;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jude.rollviewpager.OnItemClickListener;
import com.jude.rollviewpager.RollPagerView;
import com.jude.rollviewpager.hintview.ColorPointHintView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.melnykov.fab.FloatingActionButton;
import com.melnykov.fab.ScrollDirectionListener;
import com.tehui.R;
import com.tehui.activity.impl.CommodityActivity;
import com.tehui.adapter.HomeAdapter;
import com.tehui.adapter.RollViewPagerAdapter;
import com.tehui.bean.BrandData;
import com.tehui.fragment.BaseFragment;
import com.tehui.global.Global;
import com.tehui.utils.ui.UiUtils;
import com.tehui.view.CustomeUserNoticeCursor;
import com.tehui.view.CustomeUserNoticeScrollView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by jasmine on 2017/7/24.
 */

public class NineFragment extends BaseFragment implements BaseQuickAdapter.RequestLoadMoreListener, View
        .OnClickListener {

    @BindView(R.id.swipe)
    SwipeRefreshLayout   swipe;
    @BindView(R.id.nineRl)
    RecyclerView         nineRl;
    @BindView(R.id.rl)
    RelativeLayout       rl;
    @BindView(R.id.fab)
    FloatingActionButton fab;
    @BindView(R.id.llNet)
    LinearLayout         llnet;
    @BindView(R.id.tvNetError)
    TextView             tvNetError;
    @BindView(R.id.btnNet)
    Button               btnNet;
    @BindView(R.id.shop_null)
    TextView             shopNull;

    View      line1;
    View      line2;
    ImageView rDesc;
    ImageView rAesc;
    View      line3;
    ImageView jDesc;
    ImageView jAesc;
    View      line4;
    ImageView xDesc;
    ImageView xAesc;

    private              int    page          = 2;
    private              String nomalSort     = "";
    private              String nomalType     = "";
    private              String cz            = "";
    private static final int    PAGE_SIZE     = 10;

    private View                       view;
    private View                       headerView;
    private String                     clazz;
    private Timer                      timer;
    private int                        total_num;//服务器端一共多少条数据
    private List<BrandData.ResultBean> result;
    private boolean                    isRefresh;
    private boolean                    isLoadmore;
    private GridLayoutManager          gridLayoutManager;
    private HomeAdapter                homeAdapter;
    private boolean                    isRenqi;
    private boolean                    isJiage;
    private boolean                    isXiaoiang;
    private RollPagerView              mRollViewPager;

    @Override
    public View initView() {
        view = View.inflate(UiUtils.getContext(), R.layout.nine_layout, null);
        headerView = View.inflate(UiUtils.getContext(), R.layout.nine_header_view, null);
        CustomeUserNoticeScrollView scrollView = (CustomeUserNoticeScrollView) headerView.findViewById(R.id
                .scroll);
        CustomeUserNoticeCursor user_notice_cursor = (CustomeUserNoticeCursor) headerView.findViewById(R.id
                .user_notice_cursor);
        scrollView.setCursor(user_notice_cursor);
        RadioButton jinxuan = (RadioButton) headerView.findViewById(R.id.jinxuan);
        jinxuan.setChecked(true);
        return view;
    }

    @Override
    public void initData() {
        super.initData();
        fab.hide(false);
        initHomeRg();
        initSwipe();
        getWeb(1, "", "");
        initScrollButton();
        initFab();
        initRollPagerView();
        initNetError();
    }

    private void initNetError() {
        btnNet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getWeb(1, "", "");
                swipe.setRefreshing(true);
                isLoadmore = false;
                isRefresh = true;
            }
        });
    }

    //初始化轮播条
    private void initRollPagerView() {
        OkGo.get("http://dl.21tehui.com/AdImgApi.html?type=3").tag(this)
                //请求的tag,
                .cacheKey("cacheKey")                       //设置当前请求的缓存key,建议每个不同功能的请求设置一个
                .cacheMode(CacheMode.DEFAULT)              //缓存模式，详细请看缓存介绍
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        if (s != null) {
                            ArrayList<String> imageUrl = new ArrayList<>();
                            ArrayList<String> link = new ArrayList<>();
                            try {
                                JSONArray jsonArray = new JSONArray(s);
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    imageUrl.add(new JSONObject(jsonArray.get(i).toString()).get("image")
                                            .toString());
                                    link.add(new JSONObject(jsonArray.get(i).toString()).get("link")
                                            .toString());
                                }
                                initRollPagerData(imageUrl, link);
                            } catch (JSONException e) {

                            }
                        }
                    }
                });
    }

    private void initRollPagerData(ArrayList<String> imageUrl, final ArrayList<String> links) {

        //轮播条目
        mRollViewPager = (RollPagerView) headerView.findViewById(R.id.rollPagerView);
        //设置播放时间间隔
        mRollViewPager.setPlayDelay(3000);
        //设置透明度
        mRollViewPager.setAnimationDurtion(500);
        //设置指示器
        mRollViewPager.setHintView(new ColorPointHintView(UiUtils.getContext(), Color.RED, Color.GRAY));
        mRollViewPager.setHintPadding(0, 20, 0, 0);

        mRollViewPager.setAdapter(new RollViewPagerAdapter(imageUrl));
        mRollViewPager.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                String s = links.get(position);
                Intent intent = new Intent();
                intent.putExtra("goodsId", s);
                intent.putExtra("isRollView", true);
                intent.putExtra("isFromFavorite", true);
                intent.setClass(UiUtils.getContext(), CommodityActivity.class);
                startActivity(intent);
            }
        });
    }

    //返回顶部按钮
    private void initFab() {
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (gridLayoutManager != null) {
                    UiUtils.MoveToPosition(gridLayoutManager);
                    fab.hide();
                }
            }
        });

        fab.attachToRecyclerView(nineRl, new ScrollDirectionListener() {
            @Override
            public void onScrollDown() {
                fab.hide();
            }

            @Override
            public void onScrollUp() {
                fab.show();
            }

        }, new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                RecyclerView.LayoutManager layoutManager = nineRl.getLayoutManager();
                if (layoutManager instanceof LinearLayoutManager) {
                    GridLayoutManager linearManager = (GridLayoutManager) layoutManager;
                    int firstVisibleItemPosition = linearManager.findFirstVisibleItemPosition();
                    if (firstVisibleItemPosition > 5) {
                        fab.show();
                    } else {
                        fab.hide();
                    }
                }
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }
        });

    }

    private void initScrollButton() {

        CustomeUserNoticeScrollView scrollView = (CustomeUserNoticeScrollView) headerView.findViewById(R.id
                .scroll);

        CustomeUserNoticeCursor user_notice_cursor = (CustomeUserNoticeCursor) headerView.findViewById(R.id
                .user_notice_cursor);

        scrollView.setCursor(user_notice_cursor);
        RadioGroup rgClass = (RadioGroup) headerView.findViewById(R.id.rg_class);
        rgClass.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                timer.cancel();
                swipe.setRefreshing(true);
                page = 2;
                nomalSort = "";
                initSort();
                isRefresh = true;
                isLoadmore = false;
                switch (checkedId) {
                    case R.id.jinxuan:
                        clazz = "0";
                        getWeb(1, "", clazz);
                        break;
                    case R.id.woman:
                        clazz = "1";
                        getWeb(1, "", clazz);
                        break;
                    case R.id.man:
                        clazz = "9";
                        getWeb(1, "", clazz);
                        break;
                    case R.id.baby:
                        clazz = "2";
                        getWeb(1, "", clazz);
                        break;
                    case R.id.food:
                        clazz = "6";
                        getWeb(1, "", clazz);
                        break;
                    case R.id.electric:
                        clazz = "8";
                        getWeb(1, "", clazz);
                        break;
                    case R.id.shoe:
                        clazz = "5";
                        getWeb(1, "", clazz);
                        break;
                    case R.id.neiyi:
                        clazz = "10";
                        getWeb(1, "", clazz);
                        break;
                    case R.id.meizhuang:
                        clazz = "3";
                        getWeb(1, "", clazz);
                        break;
                    case R.id.game:
                        clazz = "7";
                        getWeb(1, "", clazz);
                        break;
                }
            }
        });
    }

    private void initSort() {

        line1.setVisibility(View.VISIBLE);
        line2.setVisibility(View.INVISIBLE);
        line3.setVisibility(View.INVISIBLE);
        line4.setVisibility(View.INVISIBLE);

        isRenqi = false;
        isXiaoiang = false;
        isJiage = false;

        rDesc.setVisibility(View.INVISIBLE);
        rAesc.setVisibility(View.INVISIBLE);

        jDesc.setVisibility(View.INVISIBLE);
        jAesc.setVisibility(View.INVISIBLE);

        xDesc.setVisibility(View.INVISIBLE);
        xAesc.setVisibility(View.INVISIBLE);

    }

    private void initHomeRg() {

        line1 = headerView.findViewById(R.id.line1);
        line2 = headerView.findViewById(R.id.line2);
        line3 = headerView.findViewById(R.id.line3);
        line4 = headerView.findViewById(R.id.line4);

        rDesc = (ImageView) headerView.findViewById(R.id.rDesc);
        rAesc = (ImageView) headerView.findViewById(R.id.rAesc);
        jDesc = (ImageView) headerView.findViewById(R.id.jDesc);
        jAesc = (ImageView) headerView.findViewById(R.id.jAesc);
        xDesc = (ImageView) headerView.findViewById(R.id.xDesc);
        xAesc = (ImageView) headerView.findViewById(R.id.xAesc);

        headerView.findViewById(R.id.rlZonghe).setOnClickListener(this);
        headerView.findViewById(R.id.rlRenqi).setOnClickListener(this);
        headerView.findViewById(R.id.rlJiage).setOnClickListener(this);
        headerView.findViewById(R.id.rlXiaoliang).setOnClickListener(this);
    }

    private void initSwipe() {
        swipe.setRefreshing(true);
        swipe.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light,
                android.R.color.holo_orange_light);
        swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 2;
                homeAdapter.setEnableLoadMore(false);
                isLoadmore = false;
                getWeb(1, "", "");
                isRefresh = true;
            }
        });
    }

    private void getWeb(int pages, String sort, String clazz) {
        if (!UiUtils.isNetworkAvailable()) {
            rl.setVisibility(View.GONE);
            llnet.setVisibility(View.VISIBLE);
            swipe.setRefreshing(false);
            return;
        } else {
            llnet.setVisibility(View.GONE);
            rl.setVisibility(View.VISIBLE);
        }

        if (!TextUtils.isEmpty(clazz)) {
            cz = clazz;
        }

        if (TextUtils.isEmpty(sort)) {
        } else {
            nomalSort = sort;
        }

        //设定计时器
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                sendTimeOutMsg();
            }
        }, Global.TIME_LIMIT);

        System.out.println(Global.URL_NINE + "&page=" + pages + "&type=" + nomalType + "&sort=" + nomalSort
                + "&class=" + cz);
        OkGo.get(Global.URL_NINE + "&page=" + pages + "&type=" + nomalType + "&sort=" + nomalSort +
                "&class=" + cz).tag(this)
                //请求的 tag,
                .cacheKey("cacheKey")                       //设置当前请求的缓存key,建议每个不同功能的请求设置一个
                .cacheMode(CacheMode.DEFAULT)              //缓存模式，详细请看缓存介绍
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        //解析
                        if (s.equals("-1")) {
                            rl.setVisibility(View.GONE);
                            llnet.setVisibility(View.VISIBLE);
                            swipe.setRefreshing(false);
                            timer.cancel();
                        } else {
                            parseJson(s);
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        tvNetError.setText("服务器数据异常!");
                        llnet.setVisibility(View.VISIBLE);
                        rl.setVisibility(View.GONE);
                        swipe.setRefreshing(false);
                        timer.cancel();
                    }
                });
    }

    //网络超时处理
    private void sendTimeOutMsg() {
        OkGo.getInstance().cancelTag(this);
        UiUtils.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                rl.setVisibility(View.GONE);
                llnet.setVisibility(View.VISIBLE);
                tvNetError.setText("网络连接超时!");
            }
        });
        UiUtils.toast("网络超时");
    }

    //解析
    private void parseJson(String s) {
        timer.cancel();
        BrandData brandData = JSON.parseObject(s, BrandData.class);
        total_num = brandData.data.goods_num;
        result = brandData.result;

        if (total_num == 0) {
            shopNull.setVisibility(View.VISIBLE);
        } else {
            shopNull.setVisibility(View.GONE);
        }

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                swipe.setRefreshing(false);
                if (isLoadmore) {
                    homeAdapter.addData(result);
                    homeAdapter.loadMoreComplete();
                } else {
                    if (isRefresh) {
                        homeAdapter.setNewData(result);
                        isRefresh = false;
                        homeAdapter.setEnableLoadMore(true);
                    } else {
                        initRecyclerView();
                    }
                }
            }
        }, 800);
        swipe.setEnabled(true);
    }

    //加载recyclerview
    private void initRecyclerView() {
        homeAdapter = new HomeAdapter(result);
        homeAdapter.setOnLoadMoreListener(this, nineRl);
        homeAdapter.addHeaderView(headerView);
        gridLayoutManager = new GridLayoutManager(activity, 2);
        nineRl.setLayoutManager(gridLayoutManager);
        nineRl.setAdapter(homeAdapter);
        homeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                BrandData.ResultBean o = (BrandData.ResultBean) adapter.getData().get(position);
                Intent intent = new Intent(UiUtils.getContext(), CommodityActivity.class);
                intent.putExtra("text", o.D_title);//标题
                intent.putExtra("id", o.GoodsID);//商品id
                intent.putExtra("url", o.discountLink);//优惠卷连接
                intent.putExtra("pic", o.Pic);//图
                intent.putExtra("quan", o.Quan_receive);//已领券
                intent.putExtra("num", o.Sales_num);//购买数
                intent.putExtra("time", o.Quan_time);//过期时间
                intent.putExtra("quanPrice", o.Quan_price);//优惠卷金额
                intent.putExtra("orgPrice", o.Org_Price);//原价
                intent.putExtra("price", o.Price + "");//券后价
                intent.putExtra("cid", o.Cid + "");
                intent.putExtra("IsTmall", o.IsTmall);
                intent.putExtra("Commission", o.Commission_jihua);
                //优惠券id
                intent.putExtra("quanid", o.Quan_id);

                startActivity(intent);
            }
        });
    }

    @Override
    public void onLoadMoreRequested() {
        swipe.setEnabled(false);
        if (homeAdapter.getData().size() < PAGE_SIZE) {
            homeAdapter.loadMoreEnd(false);
            swipe.setEnabled(true);
        } else {
            if (homeAdapter.getData().size() >= total_num) {
                homeAdapter.loadMoreEnd();
                swipe.setEnabled(true);
            } else {
                isLoadmore = true;
                getWeb(page, "", "");
                page++;
            }
        }
    }

    @Override
    public void onClick(View view) {
        timer.cancel();
        swipe.setRefreshing(true);
        page = 2;
        isRefresh = true;
        switch (view.getId()) {
            case R.id.rlZonghe:
                nomalType = "";
                line1.setVisibility(View.VISIBLE);
                line2.setVisibility(View.INVISIBLE);
                line3.setVisibility(View.INVISIBLE);
                line4.setVisibility(View.INVISIBLE);

                isRenqi = false;
                isXiaoiang = false;
                isJiage = false;

                rDesc.setVisibility(View.INVISIBLE);
                rAesc.setVisibility(View.INVISIBLE);

                jDesc.setVisibility(View.INVISIBLE);
                jAesc.setVisibility(View.INVISIBLE);

                xDesc.setVisibility(View.INVISIBLE);
                xAesc.setVisibility(View.INVISIBLE);

                getWeb(1, "", clazz);

                break;
            case R.id.rlRenqi:

                nomalType = "Quan_receive";

                isXiaoiang = false;
                isJiage = false;

                line1.setVisibility(View.INVISIBLE);
                line2.setVisibility(View.VISIBLE);
                line3.setVisibility(View.INVISIBLE);
                line4.setVisibility(View.INVISIBLE);

                if (isRenqi) {
                    //降序
                    rAesc.setVisibility(View.VISIBLE);
                    rDesc.setVisibility(View.INVISIBLE);
                    isRenqi = false;
                    getWeb(1, "ASC", clazz);
                } else {
                    //升序
                    rDesc.setVisibility(View.VISIBLE);
                    rAesc.setVisibility(View.INVISIBLE);
                    isRenqi = true;
                    getWeb(1, "DESC", clazz);
                }

                jDesc.setVisibility(View.INVISIBLE);
                jAesc.setVisibility(View.INVISIBLE);

                xDesc.setVisibility(View.INVISIBLE);
                xAesc.setVisibility(View.INVISIBLE);

                break;
            case R.id.rlJiage:

                nomalType = "Price";

                isRenqi = false;
                isXiaoiang = false;

                line1.setVisibility(View.INVISIBLE);
                line2.setVisibility(View.INVISIBLE);
                line4.setVisibility(View.INVISIBLE);
                line3.setVisibility(View.VISIBLE);

                if (isJiage) {

                    jDesc.setVisibility(View.VISIBLE);
                    jAesc.setVisibility(View.INVISIBLE);
                    isJiage = false;
                    getWeb(1, "DESC", clazz);

                } else {

                    jAesc.setVisibility(View.VISIBLE);
                    jDesc.setVisibility(View.INVISIBLE);
                    isJiage = true;
                    getWeb(1, "ASC", clazz);

                }

                rDesc.setVisibility(View.INVISIBLE);
                rAesc.setVisibility(View.INVISIBLE);
                xDesc.setVisibility(View.INVISIBLE);
                xAesc.setVisibility(View.INVISIBLE);

                break;
            case R.id.rlXiaoliang:

                nomalType = "Sales_num";

                isRenqi = false;
                isJiage = false;

                line1.setVisibility(View.INVISIBLE);
                line2.setVisibility(View.INVISIBLE);
                line3.setVisibility(View.INVISIBLE);
                line4.setVisibility(View.VISIBLE);

                if (isXiaoiang) {
                    xAesc.setVisibility(View.VISIBLE);
                    xDesc.setVisibility(View.INVISIBLE);
                    isXiaoiang = false;
                    getWeb(1, "ASC", clazz);
                } else {
                    xDesc.setVisibility(View.VISIBLE);
                    xAesc.setVisibility(View.INVISIBLE);
                    isXiaoiang = true;
                    getWeb(1, "DESC", clazz);
                }

                rDesc.setVisibility(View.INVISIBLE);
                rAesc.setVisibility(View.INVISIBLE);

                jDesc.setVisibility(View.INVISIBLE);
                jAesc.setVisibility(View.INVISIBLE);

                break;
        }
        isLoadmore = false;
    }
}
